package com.google.project.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.project.client.Service.MessageService;
import com.google.project.server.entity.Message;
import com.google.project.server.entity.Project;
import com.google.project.shared.MessageDTO;
import com.google.project.shared.ProjectDTO;

@SuppressWarnings("serial")
public class MessageServiceImpl extends RemoteServiceServlet implements
		MessageService {
	@Override
	public MessageDTO sendMessage(MessageDTO messageDTO, String projectId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Message message = null;
		try {
			Project project = pm.getObjectById(Project.class, projectId);
			message = new Message(messageDTO);
			project.getListOfMessage().add(message);
			pm.makePersistent(project);
		} finally {
			pm.close();
		}

		return message.toDTO();
	}

	@Override
	public List<MessageDTO> getMessageList() {
		List<MessageDTO> messageList = new ArrayList<MessageDTO>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Message.class);
		try {
			List<Message> list = (List<Message>) q.execute();
			for (Message message : list) {
				messageList.add(message.toDTO());
				
			}
		} catch (Exception e) {
			e.getMessage();
		} finally {
			pm.close();
		}
		return messageList;
	}
	//sau khi phan hoi ,update status cua cha 

	@Override
	public void updateParentMess(String parentId,int status) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Message mess=null;
		try {
			mess = pm
					.getObjectById(Message.class,parentId);
			MessageDTO messDTO=mess.toDTO();
			messDTO.setStatus(status);
			mess.updateFromDTO(messDTO);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
		
	}

	@Override
	public MessageDTO sendMessage(MessageDTO messageDTO) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Message message = null;
		try {
			message = new Message(messageDTO);
			pm.makePersistent(message);
		} finally {
			pm.close();
		}

		return message.toDTO();
	}

}
